from gmssl import sm3, func

from ..common.enums import algo_types
from . import sign_util
from app import conf

class BizSignUtil():
    "签名工具"

    algo = ''
    data = {}
    pri_key = conf.SM_PRI_KEY
    pub_key = conf.SM_PUB_KEY

    def __init__(self, pri_key='', pub_key=''):
        #self.data = data
        if pri_key:
            self.pri_key = pri_key
        if pub_key:
            self.pub_key = pub_key

    @staticmethod
    def sign_with_sm3(msg: str):
        bytes_list = func.bytes_to_list(msg.encode('utf-8'))
        hashed = sm3.sm3_hash(bytes_list)
        print('hash: ', hashed)
        return hashed
        
    @staticmethod
    def verify_with_sm3(msg: str, hashed: str):
        bytes_list = func.bytes_to_list(msg.encode('utf-8'))
        new_hashed = sm3.sm3_hash(bytes_list)
        print('hash: ', hashed)
        return hashed == new_hashed

    @staticmethod
    def sign_with_sm2(self, data):
        kv_str = self.gen_kvstr(data)
        sm_sign = sign_util.SM3WithSM2Util.signature(kv_str, self.pri_key, self.pub_key)
        return sm_sign 
    
    def sign_str_with_sm2(self, kv_str):
        sm_sign = sign_util.SM3WithSM2Util.signature(kv_str, self.pri_key, self.pub_key)
        return sm_sign 
    
    def verify_with_sm2(self, data, signature):
        kv_str = self.gen_kvstr(data)
        sm_sign = sign_util.SM3WithSM2Util.verify_signature(kv_str, signature, self.pub_key)
        return sm_sign 
    
    def verify_str_with_sm2(self, kv_str, signature):
        sm_sign = sign_util.SM3WithSM2Util.verify_signature(kv_str, signature, self.pub_key)
        return sm_sign 
    
    def sign_merc_payload_with_rsa(self):
        kv_str = self.gen_kvstr()
        rsa_sign = sign_util.SHA256WithRSAUtil.signature(kv_str, self.pri_key)
        return rsa_sign

    def gen_kvstr(self, data):
        '''
        生成 key1=value2&key2=value2 格式字符串
        '''
        kv_str = ''
        for k in sorted(self.data):
            kv_str += k + '=' + str(self.data[k]) + '&'
        kv_str = kv_str[:-1]
        return kv_str

